<?php

namespace app\admin\validate;

use app\common\business\Category;
use app\common\lib\Captcha;
use app\common\model\mysql\SystemCategory;
use think\Validate;

class Notice extends Validate
{
    protected $rule = [
        'id' => 'require',
        'title' => 'require',
        //'face_url' => 'require',
        'category_id' => 'require|checkCategory',
        //'description' => 'require',
        'content' => 'require',
    ];

    protected $scene=[
        'create'=>['title','category_id','content'],
        'update'=>['id','title','category_id','content'],
    ];

    protected $message = [
        'id' => 'ID不能为空',
        'title' => '名称不能为空',
        //'face_url' => '封面图不能为空',
        'category_id' => '分类不能为空',
        //'description' => '描述不能为空',
        'content' => '内容不能为空',
    ];

    protected function checkCategory($value, $rule, $data = [])
    {
        return $this->checkCommonCategory('新闻分类',$value);
    }
    protected function checkCommonCategory($name,$value)
    {
        $categoryModel = new SystemCategory();
        $categoryBis = new Category();
        try {
            $data = $categoryModel->getById($value,'id,pid');
            if ($data){
                if ($data['pid'] == 1){
                    //新闻分类下的主分类
                    $categoryBis->checkValidValueByName($name,$value);
                }else{
                    //新闻分类下的子分类
                    $parentData = $categoryModel->getById($data['pid'],'id,pid,name');
                    if ($parentData){
                       if ($parentData['pid'] != 1){
                           return '新闻分类异常';
                       }
                    }else{
                        return '父级分类不存在';
                    }
                }
            }else{
                return '分类不存在';
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return true;
    }
}
